package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.commons.templates.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.Settings;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.db.QuestionApi;
import com.tanhua.dubbo.api.db.SettingsApi;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.dubbo.api.mongo.UserLikeApi;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.utils.GetAgeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户信息业务逻辑处理层
 */
@Service
@Slf4j
public class UserInfoService {

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserService userService;

    @Reference
    private QuestionApi questionApi;

    @Reference
    private SettingsApi settingsApi;

    @Reference
    private FriendApi friendApi;//互相喜欢数量查询

    @Reference
    private UserLikeApi userLikeApi;//我的喜欢 、 粉丝 数量

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    /**
     * 查询用户信息
     */
    public UserInfoVo queryUserInfo(Long userID, Long huanxinID) {
        Long currentUserId;
        Long userId = UserHolder.getUserId();//用户id
        //3.根据userID huanxinID如果不为空使用此值

        if (!StringUtils.isEmpty(userID)) {
            currentUserId = userID;
        } else if (!StringUtils.isEmpty(huanxinID)) {
            currentUserId = huanxinID;
        } else {
            //4.如果userID huanxinID则使用token中获取的userId
            currentUserId = userId;
        }
        //5.根据userId调用服务根据用户id查询用户信息UserInfo
        UserInfo userInfo = userInfoApi.queryUserInfo(currentUserId);
        //6.将UserInfo转为UserInfoVo
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        //7.age处理下 Integer 转为String
        userInfoVo.setAge(String.valueOf(userInfo.getAge()));
        //8.返回
        return userInfoVo;
    }

    /**
     * 更新用户信息
     */
    public void updateUserInfo(UserInfoVo userInfoVo) {
        Long userId = UserHolder.getUserId();//用户id
        //3.根据用户id调用用户信息服务方法更新
        UserInfo userInfo = new UserInfo();
        //将userInfoVo转为userInfo
        BeanUtils.copyProperties(userInfoVo, userInfo);
        userInfo.setId(userId);//当前用户id
        //根据出生年月日 计算 年龄
        if (!StringUtils.isEmpty(userInfoVo.getBirthday())) {
            userInfo.setAge(GetAgeUtil.getAge(userInfoVo.getBirthday()));
        }
        userInfoApi.updateUserInfo(userInfo);
    }

    /**
     * 用户通用设置 - 查询
     */
    public SettingsVo querySettings() {
        Long userId = UserHolder.getUserId();
        //a.根据用户id查询问题
        Question question = questionApi.queryByUserId(userId);
        String txt = "";
        if (question == null || StringUtils.isEmpty(question.getTxt())) {
            //如果为空 设置默认问题
            txt = "约吗?";
        } else {
            txt = question.getTxt();
        }
        //b.根据用户id查询手机号
        String mobile = UserHolder.getUser().getMobile();
        //c.根据用户id查询通知设置
        Settings settings = settingsApi.queryByUserId(userId);
        if (settings == null) {
            //如果为空 设置默认值
            settings = new Settings();
            settings.setGonggaoNotification(false);
            settings.setPinglunNotification(false);
            settings.setLikeNotification(false);
        }
        // d.将以上调用服务结果封装Vo返回

        SettingsVo settingsVo = new SettingsVo();
        BeanUtils.copyProperties(settings,settingsVo);
        settingsVo.setId(userId);//用户id
        settingsVo.setStrangerQuestion(txt);//用户的问题
        settingsVo.setPhone(mobile);//用户手机号
        return settingsVo;
    }

    /**
     * 用户通用设置 - 修改
     */
    public void updateSettings(Boolean likeNotification, Boolean pinglunNotification, Boolean gonggaoNotification) {
        //1.根据当前用户id查询通用设置表 
        Long userId = UserHolder.getUserId();
        Settings settings = settingsApi.queryByUserId(userId);
        //2.如果记录不存在，则保存通用设置表
        if(settings == null){
            settings = new Settings();
            settings.setUserId(userId);//设置用户id
            settings.setLikeNotification(likeNotification);//喜欢通知
            settings.setPinglunNotification(pinglunNotification);//评论通知
            settings.setGonggaoNotification(gonggaoNotification);//公告通知
            settingsApi.saveSettings(settings);
        }
        //3.如果记录存在，更新通用设置表
        else
        {
            settings.setLikeNotification(likeNotification);//喜欢通知
            settings.setPinglunNotification(pinglunNotification);//评论通知
            settings.setGonggaoNotification(gonggaoNotification);//公告通知
            settingsApi.updateByUserId(settings);
        }
    }

    /**
     * 互相喜欢，喜欢，粉丝 - 统计
     */
    public CountsVo queryCounts() {
        Long userId = UserHolder.getUserId();
        //1.互相喜欢：调用服务查询好友表数量
        Long eachLoveCount = friendApi.count(userId);
        //2.喜欢：调用服务查询我的喜欢数量userId=xxx 查询likeUserId数量
        Long loveCount = userLikeApi.countByUserId(userId);
        //3.粉丝:调用服务查询我的喜欢数量likeUserId=xxx 查询userId数量
        Long fanCount = userLikeApi.countByLikeUserId(userId);
        CountsVo vo = new CountsVo();
        vo.setEachLoveCount(eachLoveCount);
        vo.setLoveCount(loveCount);
        vo.setFanCount(fanCount);
        return vo;
    }

    /**
     * 互相喜欢，喜欢，粉丝、谁看过我 - 分页查询
     * 1 互相关注
     * 2 我关注
     * 3 粉丝
     * 4 谁看过我
     */
    public PageResult<FriendVo> queryFriendsByPage(int type, int page, int pagesize) {
        PageResult<FriendVo> voPageResult = new PageResult<>();

        Long userId = UserHolder.getUserId();//当前用户id
        PageResult<RecommendUser> pageResult = new PageResult<>();
        //1.根据不同的类型 分页查询数据
        switch (type){
            case 1:
                //互相关注
                pageResult = userLikeApi.findPageLikeEachOther(userId,page,pagesize);
                break;
            case 2:
                //2 我关注
                pageResult = userLikeApi.findPageOneSideLike(userId,page,pagesize);
                break;
            case 3:
                //3 粉丝
                pageResult = userLikeApi.findPageFens(userId,page,pagesize);
                break;
            case 4:
                //4 谁看过我
                pageResult = userLikeApi.findPageMyVisitors(userId,page,pagesize);
                break;
            default: break;
        }
        if(pageResult == null || CollectionUtils.isEmpty(pageResult.getItems())){
            return new PageResult<>(0l,10l,0l,1l,null);
        }
        //2.从分页对象中获取推荐用户数据 循环遍历查询用户信息
        List<FriendVo> friendVoList = new ArrayList<>();
        for (RecommendUser recommendUser : pageResult.getItems()) {
            FriendVo friendVo = new FriendVo();
            UserInfo userInfo = userInfoApi.queryUserInfo(recommendUser.getUserId());//根据要展示的用户id作为条件查询
            BeanUtils.copyProperties(userInfo,friendVo);//展示的用户信息
            friendVo.setMatchRate(recommendUser.getScore().intValue());//缘分值（匹配度）
            friendVoList.add(friendVo);
        }
        //3.封装Vo返回
        BeanUtils.copyProperties(pageResult,voPageResult);
        voPageResult.setItems(friendVoList);
        return voPageResult;
    }

    /**
     * 粉丝-喜欢
     */
    public void makeFriends(Long friendId) {
        Long userId = UserHolder.getUserId();
        //1.根据当前用户id 与 好友id 删除UserLike中 粉丝-喜欢记录
        userLikeApi.deleteById(userId,friendId);
        //2.往好友表tanhua_users表中保存2条记录
        Friend friend = new Friend();
        friend.setUserId(userId);
        friend.setFriendId(friendId);
        friendApi.saveFriend(friend);
        //3.调用环信交友方法
        huanXinTemplate.makeFriends(userId,friendId);
        log.debug("粉丝{}-喜欢{}成功了",friendId,userId);
    }
}
